<?php
class login extends base{

	public function init(){
		parent::init();

		$this->tit = '登录';
		$this->modelObj = D('company_admin');
		$this->cateObj = D('company_cate');
		$this->zoneObj = D('company_zone');
		$this->bingchuangObj = D('company_bingchuang');
		$this->companyObj = D('company');

		$this->userObj = D('company_user');
		$this->sys_userObj = D('sys_user');

		$this->appid = 'wx913120c9717ff5d3';
    	$this->appsecret = '8a284b6f7fbeaa91007f036363eae369';
	}

	public function index(){
		if($this->fmdo=='login'){

			$username = arg('username');
			$password = arg('password');

			$tel = arg('tel');

			if (empty($username)) {
				$this->renderError('用户名不能为空');
			}
	        $data = $this->modelObj->check_login($tel);
	        if($data){
				// dump($admin);exit;
	        	$_SESSION["company_user"] = $data['admin'];
				$_SESSION["token"] = $data['token'];
	            $this->modelObj->up_time($data['id']);

	            //自动登录
            	if(arg('remember')){
					$this->set_cookie('m_user',$username);
					$this->set_cookie('m_pass',$password);
					$this->set_cookie('remember','1');
				}else{
					$this->set_cookie('m_pass','');
					$this->set_cookie('remember','');
				}

	        	$this->renderSuccess('登录成功',"/{$this->module}/main/index");

	        }else{
	            $this->renderError('登录失败');
	        }

		}
	}

	public function reg(){
		$this->zone_id = arg('zone_id');
		if($this->zone_id){
			$this->zone = $this->zoneObj->findById($this->zone_id);
			$this->zone_arr = $this->zoneObj->get_zone_ids($this->zone_id);
			sort($this->zone_arr);
			$this->zone_ids = implode(',',$this->zone_arr);

			$cates = $this->cateObj->findAll(array("status=1"));
			if($cates){
				foreach($cates as $val){
					$cates_arr[] = $val['id'];
				}
			}
			$this->cate_ids = implode(',',$cates_arr);
		}

		// dump($this->cate_ids);exit;

		if($this->fmdo=='reg'){

			$username = arg('username');
			$password = arg('password');
			$realname = arg('realname');

			if (empty($username)) {
				$this->renderError('手机号不能为空');
			}
	        $admin = $this->modelObj->check_user($username);
	        if($admin){
				$arrBase = array(
					'company_id'=>$this->zone['company_id'],
					'level' => 1,
					'realname' => $realname,
					// 'username' => $username,
					// 'tel' => $username,
					'password' => qcing_hash($password),
					'add_time' => date('Y-m-d H:i:s'),
					'status'=>1,
					'cate_ids'=>$this->cate_ids,
					'zone_ids'=>$this->zone_ids
				);
				$this->modelObj->edit($admin['id'],$arrBase);

	        }else{

				$arrBase = array(
					'company_id'=>$this->zone['company_id'],
					'level' => 1,
					'realname' => $realname,
					'username' => $username,
					'tel' => $username,
					'password' => qcing_hash($password),
					'add_time' => date('Y-m-d H:i:s'),
					'status'=>1,
					'zone_ids'=>$this->zone_ids,
					'cate_ids'=>$this->cate_ids
				);
				$this->modelObj->add($arrBase);

	        }


			$this->renderSuccess('绑定成功',"/{$this->module}/my/index");

		}
	}

	// 退出
	public function logout(){
		// 这里是PHP.net关于删除SESSION的方法
		$_SESSION = array();
		if (isset($_COOKIE[session_name()])) {setcookie(session_name(), '', time()-42000, '/');}
		session_destroy();
		$this->redirect("/{$this->module}/login/index");
	}

	//验证码
	public function verify(){
		$config = array(
			'fontSize'   => 18,
			'length'     => 4,
			'useNoise'   => false,
		);
		$verify = new Verify($config);
		$verify->fontttf = '4.ttf';
		$verify->codeSet = '0123456789';
		$verify->entry();
	}


	function wxlogin() {

		$from = arg('from');
        $wxstate = md5(uniqid(rand(), TRUE));
        $_SESSION["wxstate"] = $wxstate;
        $_SESSION["method"] = 'login';
		$callback_url = "http://t.20m.cn/index_admin/login/wxcallback?from={$from}";
        $login_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri=' .urlencode($callback_url). '&response_type=code&scope=snsapi_userinfo&state=' . $wxstate . '#wechat_redirect';
        header("Location:$login_url");
        die;
    }


    //微信回调
    function wxcallback() {
    	$wxstate = $_SESSION["wxstate"];
		$state = arg('state');

		$from = arg('from');
		// dump($from);exit;
        if( arg('state') == $wxstate) {

            $code = arg('code');
            if (empty($code)){
                $this->renderError('授权后才能登陆！');
            }

			$this->curl = new \lib\Curl();

            $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid .
                    '&secret=' . $this->appsecret .
                    '&code=' . $code . '&grant_type=authorization_code';
            $str = $this->curl->get($token_url);

            $params = json_decode($str, true);
            if (!empty($params['errcode'])) {
                echo "<h3>error:</h3>" . $params['errcode'];
                echo "<h3>msg  :</h3>" . $params['errmsg'];
                exit;
            }
            if (empty($params['openid'])) {
                $this->renderError('登录失败');
            }

			$info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$params['access_token'].'&openid='.$params['openid'].'&lang=zh_CN';
			// $info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$this->accessToken.'&openid='.$params['openid'].'&lang=zh_CN';
			$info = $this->curl->get($info_url);
			$info = json_decode($info,true);

            //查找用户
            $sys_user = $this->sys_userObj->find(array('open_id' => $params['openid'], ));
            if($sys_user){
            	$arrBase = array(
	                // 'open_id' => $params['openid'],
	                'token' => $params['refresh_token'],
					'nickname'   => $info['nickname'],
					'avatarUrl'   => $info['headimgurl'],
	                'up_time'   => date("Y-m-d H:i:s"),
	                'status' => 1,
	            );
	            $this->sys_userObj->edit($sys_user['id'],$arrBase);
				$wxuser_id = $sys_user['id'];
            }else{
            	$arrBase = array(
	                'open_id' => $params['openid'],
	                'token' => $params['refresh_token'],
	                'nickname'   => $info['nickname'],
					'avatarUrl'   => $info['headimgurl'],
	                'gender'   => $info['sex'],
	                'add_time'   => date("Y-m-d H:i:s"),
	                'status' => 1,
	            );
	            $wxuser_id = $this->sys_userObj->add($arrBase);
            }

			if($wxuser_id){
				$cond = "status=1 and wxuser_id='{$wxuser_id}' and company_id='{$this->company['id']}'";
				$user = $this->userObj->find(array($cond));
				if($user){
					$arrBase = array(
						'nickname'   => $info['nickname'],
						'avatarUrl'   => $info['headimgurl'],
						'up_time'   => date("Y-m-d H:i:s"),
						'status' => 1,
					);
					$this->userObj->edit($user['id'],$arrBase);
					$user_id = $user['id'];
				}else{
					$arrBase = array(
						'company_id' => $this->company['id'],
						'nickname'   => $info['nickname'],
						'avatarUrl'   => $info['headimgurl'],
						'sex'   => $info['sex'],
						'wxuser_id'=> $wxuser_id,
						'add_time'   => date("Y-m-d H:i:s"),
						'status' => 1,
					);
					$user_id = $this->userObj->add($arrBase);
				}
				// $_SESSION["company_user"]['id'] = $user_id;
			}

			// 判断admin
			$cond = "status=1 and user_id='{$user_id}'";
            $admin = $this->modelObj->find(array($cond));
            if($admin){
				$_SESSION["company_user"]['id'] = $admin['id'];
	            $this->modelObj->up_time($admin['id']);
			}
			if($from){
				$url = $from;
			}else{
				$url = "/index_admin/my/index";
			}

			$this->redirect($url);
        }
    }

}